<template>
  <view class="create-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <text class="back-text">返回</text>
        </view>
        <view class="title">
          <text class="title-text">{{ isEdit ? '编辑采购单' : '创建采购单' }}</text>
        </view>
        <view class="save-btn" @click="submitForm">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 表单内容 -->
    <scroll-view class="form-container" scroll-y="true">
      <view class="form-content">
        <!-- 菜单日期 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">菜单日期 *</text>
          </view>
          <view class="form-input" @click="showDatePicker = true">
            <text class="input-text" :class="{ placeholder: !formData.menu_date }">
              {{ formData.menu_date || '请选择菜单日期' }}
            </text>
            <image src="/static/image/icon_arrow_right.png" class="arrow-icon" mode="aspectFit"></image>
          </view>
        </view>

        <!-- 菜单标题 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">采购单标题 *</text>
          </view>
          <view class="form-input">
            <input
              type="text"
              v-model="formData.title"
              placeholder="请输入菜单标题"
              class="input-field"
              maxlength="255"
            />
          </view>
        </view>

        <!-- 供应商 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">供应商 *</text>
          </view>
          <view class="form-input" >
            <text class="input-text" :class="{ placeholder: !selectedSupplier }">
              {{ selectedSupplier || '-' }}
            </text>
            <!-- <image src="/static/image/icon_arrow_right.png" class="arrow-icon" mode="aspectFit"></image> -->
          </view>
        </view>

        <!-- 采购员 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">采购员 *</text>
          </view>
          <view class="form-input">
            <text class="input-text" :class="{ placeholder: !selectedPurchaser }">
              {{ selectedPurchaser || '暂未登录' }}
            </text>
            <!-- <image src="/static/image/icon_arrow_right.png" class="arrow-icon" mode="aspectFit"></image> -->
          </view>
        </view>

        <!-- 菜单描述 -->
        <view class="form-item">
          <view class="form-label">
            <text class="label-text">菜单描述</text>
          </view>
          <view class="form-input">
            <textarea
              v-model="formData.description"
              placeholder="请输入菜单描述（选填）"
              class="textarea-field"
              maxlength="1000"
              :show-confirm-bar="false"
            />
            <view class="char-count">
              <text class="count-text">{{ formData.description.length }}/1000</text>
            </view>
          </view>
        </view>

        <!-- 状态（编辑模式显示） -->
        <!-- <view v-if="isEdit" class="form-item">
          <view class="form-label">
            <text class="label-text">状态</text>
          </view>
          <view class="form-input" @click="showStatusPicker = true">
            <text class="input-text" :class="{ placeholder: !selectedStatus }">
              {{ selectedStatus || '请选择状态' }}
            </text>
            <image src="/static/image/icon_arrow_right.png" class="arrow-icon" mode="aspectFit"></image>
          </view>
        </view> -->
      </view>
    </scroll-view>

    <!-- 日期选择器 -->
    <!-- <u-datetime-picker
      v-model="showDatePicker"
      mode="date"
      :value="formData.menu_date"
      @confirm="onDateConfirm"
    /> -->
    <u-picker mode="time" v-model="showDatePicker" :params="dateParams" @confirm="onDateConfirm"></u-picker>

    <!-- 供应商选择器 -->
    <u-popup v-model="showSupplierPicker" mode="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <view class="picker-cancel" @click="showSupplierPicker = false">
            <text class="picker-btn-text">取消</text>
          </view>
          <view class="picker-title">
            <text class="picker-title-text">选择供应商</text>
          </view>
          <view class="picker-confirm" @click="confirmSupplier">
            <text class="picker-btn-text">确定</text>
          </view>
        </view>
        <picker-view
          :value="supplierIndex"
          @change="onSupplierChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(supplier, index) in supplierList" :key="index">
              <text class="picker-item-text">{{ supplier.name }}</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </u-popup>

    <!-- 采购员选择器 -->
    <u-popup v-model="showPurchaserPicker" mode="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <view class="picker-cancel" @click="showPurchaserPicker = false">
            <text class="picker-btn-text">取消</text>
          </view>
          <view class="picker-title">
            <text class="picker-title-text">选择采购员</text>
          </view>
          <view class="picker-confirm" @click="confirmPurchaser">
            <text class="picker-btn-text">确定</text>
          </view>
        </view>
        <picker-view
          :value="purchaserIndex"
          @change="onPurchaserChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(purchaser, index) in purchaserList" :key="index">
              <text class="picker-item-text">{{ purchaser.name }}</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </u-popup>

    <!-- 状态选择器 -->
    <u-popup v-model="showStatusPicker" mode="bottom">
      <view class="picker-container">
        <view class="picker-header">
          <view class="picker-cancel" @click="showStatusPicker = false">
            <text class="picker-btn-text">取消</text>
          </view>
          <view class="picker-title">
            <text class="picker-title-text">选择状态</text>
          </view>
          <view class="picker-confirm" @click="confirmStatus">
            <text class="picker-btn-text">确定</text>
          </view>
        </view>
        <picker-view
          :value="statusIndex"
          @change="onStatusChange"
          class="picker-view"
        >
          <picker-view-column>
            <view class="picker-item" v-for="(status, index) in statusList" :key="index">
              <text class="picker-item-text">{{ status.name }}</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import api from "../../config/api.js";

export default {
  data() {
    return {
      isEdit: false,
      workorderId: '',
      formData: {
        menu_date: '',
        title: '',
        description: '',
        supplier_id: '',
        purchaser_id: '',
        status: 0
      },
      selectedSupplier: '',
      selectedPurchaser: '',
      selectedStatus: '',
      supplierList: [],
      purchaserList: [],
      supplierIndex: 0,
      purchaserIndex: 0,
      statusIndex: 0,
      showDatePicker: false,
      showSupplierPicker: false,
      showPurchaserPicker: false,
      showStatusPicker: false,
      submitting: false,

      // 状态列表
      statusList: [
        { key: 0, name: '草稿' },
        { key: 1, name: '待采购' },
        { key: 2, name: '采购中' },
        { key: 3, name: '已收货' },
        { key: 4, name: '已完成' }
      ],
      dateParams: {
        year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
      }
    }
  },

  onLoad(options) {
    this.$store.dispatch('getUserInfo')
    if (options.id) {
      this.isEdit = true;
      this.workorderId = options.id;
      this.loadEditData();
    } else {
      this.selectedPurchaser = this.userInfo.name
      this.formData.purchaser_id = this.userInfo.id
      console.log(this.selectedPurchaser, '----')
    }
    // this.loadPurchaserData();
  },

  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 加载编辑数据
    loadEditData() {
      api.getDailyMenu(this.workorderId).then(response => {
        this.formData = { ...response };

        // 设置选中的值
        if (response.supplier) {
          this.selectedSupplier = response.supplier.name;
        }
        if (response.purchaser) {
          this.selectedPurchaser = response.purchaser.name;
        }

        // 设置状态
        const statusItem = this.statusList.find(item => item.key === response.status);
        if (statusItem) {
          this.selectedStatus = statusItem.name;
          this.statusIndex = this.statusList.findIndex(item => item.key === response.status);
        }

        // 根据日期加载供应商
        if (response.menu_date) {
          this.loadSuppliersByDate(response.menu_date);
        }

      }).catch(error => {
        console.error('加载采购单数据失败:', error);
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      });
    },

    // 根据日期加载供应商
    async loadSuppliersByDate(dateString) {
      try {
        const month = this.getMonthFromDate(dateString);
        const monthlyBidding = await api.getMonthlyBiddingList({
          month: month,
          status: 3
        });

        if (monthlyBidding && monthlyBidding.length > 0) {
          const bidding = monthlyBidding[0];
          if (bidding.supplier) {
            this.supplierList = [bidding.supplier];
            this.supplierIndex = 0;
          }
        }
      } catch (error) {
        console.error('加载供应商失败:', error);
      }
    },

    // 加载采购员数据
    loadPurchaserData() {
      api.getPurchaserList({ status: 1 }).then(response => {
        if (response && response.length > 0) {
          this.purchaserList = response;

          // 如果是编辑模式，设置采购员索引
          if (this.isEdit && this.formData.purchaser_id) {
            const index = this.purchaserList.findIndex(item => item.id === this.formData.purchaser_id);
            if (index !== -1) {
              this.purchaserIndex = index;
            }
          }
        }
      }).catch(error => {
        console.error('加载采购员列表失败:', error);
        uni.showToast({
          title: '加载采购员列表失败',
          icon: 'none'
        });
      });
    },

    // 日期选择确认
    onDateConfirm(e) {
      console.log(e, '----')
      this.formData.menu_date = `${e.year}-${e.month}-${e.day}`
      this.showDatePicker = false;
      // 清空供应商选择
      this.formData.supplier_id = '';
      this.selectedSupplier = '';
      this.supplierList = [];

      // 根据日期自动选择供应商
      this.autoSelectSupplier();
    },

    // 自动选择供应商
    async autoSelectSupplier() {
      if (!this.formData.menu_date) return;

      try {
        const month = this.getMonthFromDate(this.formData.menu_date);
        const monthlyBidding = await api.getMonthlyBiddingList({
          month: month,
          status: 3
        });

        if (monthlyBidding && monthlyBidding.length > 0) {
          const bidding = monthlyBidding[0];
          if (bidding.supplier) {
            this.supplierList = [
              {
                  value: bidding.supplier.id,
                  label: bidding.supplier.name
                }
            ];
            this.supplierIndex = 0;
            this.formData.supplier_id = bidding.supplier.id;
            this.selectedSupplier = bidding.supplier.name;
          }
        } else {
          uni.showToast({
            title: '该月份未确定供应商，请先确定供应商',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('自动选择供应商失败:', error);
        uni.showToast({
          title: '加载供应商失败',
          icon: 'none'
        });
      }
    },

    // 从日期获取月份
    getMonthFromDate(dateString) {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },

    // 供应商选择变化
    onSupplierChange(e) {
      this.supplierIndex = e.detail.value[0];
    },

    // 确认供应商选择
    confirmSupplier() {
      if (this.supplierList.length > 0) {
        const supplier = this.supplierList[this.supplierIndex];
        this.formData.supplier_id = supplier.id;
        this.selectedSupplier = supplier.name;
      }
      this.showSupplierPicker = false;
    },

    // 采购员选择变化
    onPurchaserChange(e) {
      this.purchaserIndex = e.detail.value[0];
    },

    // 确认采购员选择
    confirmPurchaser() {
      if (this.purchaserList.length > 0) {
        const purchaser = this.purchaserList[this.purchaserIndex];
        this.formData.purchaser_id = purchaser.id;
        this.selectedPurchaser = purchaser.name;
      }
      this.showPurchaserPicker = false;
    },

    // 状态选择变化
    onStatusChange(e) {
      this.statusIndex = e.detail.value[0];
    },

    // 确认状态选择
    confirmStatus() {
      if (this.statusList.length > 0) {
        const status = this.statusList[this.statusIndex];
        this.formData.status = status.key;
        this.selectedStatus = status.name;
      }
      this.showStatusPicker = false;
    },

    // 表单验证
    validateForm() {
      if (!this.formData.menu_date) {
        uni.showToast({
          title: '请选择菜单日期',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.title || this.formData.title.trim() === '') {
        uni.showToast({
          title: '请输入菜单标题',
          icon: 'none'
        });
        return false;
      }

      if (this.formData.title.length < 2) {
        uni.showToast({
          title: '菜单标题长度不能少于2个字符',
          icon: 'none'
        });
        return false;
      }

      if (this.formData.title.length > 255) {
        uni.showToast({
          title: '菜单标题长度不能超过255个字符',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.supplier_id) {
        uni.showToast({
          title: '请选择供应商',
          icon: 'none'
        });
        return false;
      }

      if (!this.formData.purchaser_id) {
        uni.showToast({
          title: '请选择采购员',
          icon: 'none'
        });
        return false;
      }

      if (this.formData.description && this.formData.description.length > 1000) {
        uni.showToast({
          title: '菜单描述长度不能超过1000个字符',
          icon: 'none'
        });
        return false;
      }

      return true;
    },

    // 提交表单
    submitForm() {
      if (this.submitting) return;

      if (!this.validateForm()) return;

      this.submitting = true;

      const apiMethod = this.isEdit ?
        api.updateDailyMenu(this.workorderId, this.formData) :
        api.createDailyMenu(this.formData);

      apiMethod.then(response => {
        uni.showToast({
          title: this.isEdit ? '更新成功' : '创建成功',
          icon: 'success'
        });

        // 返回上一页并刷新列表
        setTimeout(() => {
          uni.navigateBack();
        }, 1000);

      }).catch(error => {
        console.error(this.isEdit ? '更新采购单失败:' : '创建采购单失败:', error);

      }).finally(() => {
        this.submitting = false;
      });
    }
  }
}
</script>

<style lang="scss">
.create-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

// 顶部导航
.header {
  background-color: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .back-btn {
      .back-text {
        font-size: 32rpx;
        color: #666;
      }
    }

    .title {
      .title-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .save-btn {
      .save-text {
        font-size: 32rpx;
        color: #FFC300;
        font-weight: 500;
      }
    }
  }
}

// 表单容器
.form-container {
  height: calc(100vh - 120rpx);
}

.form-content {
  padding: 32rpx;
}

// 表单项
.form-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;

  .form-label {
    margin-bottom: 24rpx;

    .label-text {
      font-size: 32rpx;
      color: #333;
      font-weight: 500;
    }
  }

  .form-input {
    position: relative;

    .input-text {
      font-size: 32rpx;
      color: #333;
      line-height: 1.5;

      &.placeholder {
        color: #999;
      }
    }

    .input-field {
      width: 100%;
      font-size: 32rpx;
      color: #333;
      line-height: 1.5;
    }

    .textarea-field {
      width: 100%;
      font-size: 32rpx;
      color: #333;
      line-height: 1.5;
      min-height: 120rpx;
    }

    .arrow-icon {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 32rpx;
      height: 32rpx;
    }

    .char-count {
      text-align: right;
      margin-top: 16rpx;

      .count-text {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

// 选择器容器
.picker-container {
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;

  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 32rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .picker-cancel {
      .picker-btn-text {
        font-size: 32rpx;
        color: #666;
      }
    }

    .picker-title {
      .picker-title-text {
        font-size: 36rpx;
        color: #333;
        font-weight: 600;
      }
    }

    .picker-confirm {
      .picker-btn-text {
        font-size: 32rpx;
        color: #FFC300;
        font-weight: 500;
      }
    }
  }

  .picker-view {
    height: 400rpx;

    .picker-item {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 80rpx;

      .picker-item-text {
        font-size: 32rpx;
        color: #333;
      }
    }
  }
}
</style>
